﻿using Autofac;
using System.Runtime.CompilerServices;

namespace RayD.Core
{
    /// <summary>
    /// Autofac容器(不使用构造函数的情况下注入实例)
    /// </summary>
    public static class ServiceContainer
    {

        /// <summary>
        /// 初始化服务获取类
        /// </summary>
        /// <param name="engine"></param>
        /// <returns></returns>
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static IContainer Initialize(IContainer container)
        {
            if (Current == null)
                Current = container;
            return Current;
        }

        /// <summary>
        /// 当前服务
        /// </summary>
        public static IContainer Current { get; private set; }
    }


    /// <summary>
    /// 扩展方法
    /// </summary>
    public static partial class Extention
    {
        /// <summary>
        /// 获取生命周期实例(相当于每次获取会new一个)
        /// </summary>
        /// <typeparam name="T">获取实例类型</typeparam>
        /// <param name="container">Autofac容器</param>
        /// <returns></returns>
        public static T GetInstance<T>(this IContainer container) where T : class
        {
            using (var scope = container.BeginLifetimeScope())
            {
                return scope.Resolve<T>();
            }
        }
    }
}
